package com.lanou.renrenxin.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.toolbox.NetworkImageView;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.lanou.renrenxin.R;
import com.lanou.renrenxin.custommodule.ProcessImageView;
import com.lanou.renrenxin.dao.ChatList;
import com.lanou.renrenxin.onclicklistener.OnChattingItemClickListener;
import com.lanou.renrenxin.singleton.RenrenxinSingleton;
import com.lanou.renrenxin.tools.StringValues;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zouhui on 16/3/3.
 */
public class ChattingAdapter extends RecyclerView.Adapter {
    private final static int MSG_TYPE_RECEIVE = 1;
    private final static int MSG_TYPE_SEND = 2;
    private final static int MSG_TYPE_SEND_TXT = 21;//文本
    private final static int MSG_TYPE_SEND_VOICE = 22;//声音
    private final static int MSG_TYPE_SEND_VIDEO = 23;//视频
    private final static int MSG_TYPE_SEND_FILE = 24;//文件
    private final static int MSG_TYPE_SEND_LOCATION = 25;//定位
    private final static int MSG_TYPE_SEND_IMAGE = 26;//图片
    private final static int MSG_TYPE_RECEIVE_TXT = 11;
    private final static int MSG_TYPE_RECEIVE_VOICE = 12;//声音
    private final static int MSG_TYPE_RECEIVE_VIDEO = 13;//视频
    private final static int MSG_TYPE_RECEIVE_FILE = 14;//文件
    private final static int MSG_TYPE_RECEIVE_LOCATION = 15;//定位
    private final static int MSG_TYPE_RECEIVE_IMAGE = 16;//图片
    private Context context;
    private List<ChatList> data;
    private EMConversation conversation;
    private String toUserName;
    private String mUsernmae;
    private int sendViewCount;
    private OnChattingItemClickListener onChattingItemClickListener;
    private String msgType;

    public void setOnChattingItemClickListener(OnChattingItemClickListener onChattingItemClickListener) {
        this.onChattingItemClickListener = onChattingItemClickListener;
    }

    public int getSendViewCount() {
        return sendViewCount;
    }

    public void setSendViewCount(int sendViewCount) {
        this.sendViewCount = sendViewCount;
    }

    public ChattingAdapter(Context context, String toUserName, String mUsernmae) {
        this.context = context;
        this.toUserName = toUserName;
        this.mUsernmae = mUsernmae;
        data = new ArrayList<>();
        initData();
    }

    private void initData() {

        conversation = EMChatManager.getInstance().getConversation(toUserName);
        List<EMMessage> emMessageList = conversation.getAllMessages();
        for (int i = 0; i < emMessageList.size(); i++) {
            ChatList chattingBean = new ChatList();


            if (emMessageList.get(i).getFrom().equals(toUserName)) {//接收
                if (emMessageList.get(i).getType() == EMMessage.Type.TXT) {
                    chattingBean.setBody(((TextMessageBody) emMessageList.get(i).getBody()).getMessage());
                    msgType = StringValues.MSG_TYPE_TXT;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.FILE) {
                    msgType = StringValues.MSG_TYPE_FILE;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.IMAGE) {
                    msgType = StringValues.MSG_TYPE_IMAGE;
                    chattingBean.setBody(((ImageMessageBody) emMessageList.get(i).getBody()).getRemoteUrl());
                } else if (emMessageList.get(i).getType() == EMMessage.Type.LOCATION) {
                    msgType = StringValues.MSG_TYPE_LOCATION;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.VOICE) {
                    chattingBean.setBody(((VoiceMessageBody) emMessageList.get(i).getBody()).getLocalUrl());
                    chattingBean.setVoiceLen(((VoiceMessageBody) emMessageList.get(i).getBody()).getLength());
                    msgType = StringValues.MSG_TYPE_VOICE;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.VIDEO) {
                    msgType = StringValues.MSG_TYPE_VIDEO;
                }
                chattingBean.setType(MSG_TYPE_RECEIVE);
            } else {//发送
                if (emMessageList.get(i).getType() == EMMessage.Type.TXT) {
                    chattingBean.setBody(((TextMessageBody) emMessageList.get(i).getBody()).getMessage());
                    msgType = StringValues.MSG_TYPE_TXT;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.FILE) {
                    msgType = StringValues.MSG_TYPE_FILE;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.IMAGE) {
                    msgType = StringValues.MSG_TYPE_IMAGE;
                    chattingBean.setBody(((ImageMessageBody) emMessageList.get(i).getBody()).getLocalUrl());
                } else if (emMessageList.get(i).getType() == EMMessage.Type.LOCATION) {
                    msgType = StringValues.MSG_TYPE_LOCATION;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.VOICE) {
                    chattingBean.setVoiceLen(((VoiceMessageBody) emMessageList.get(i).getBody()).getLength());
                    chattingBean.setBody(((VoiceMessageBody) emMessageList.get(i).getBody()).getLocalUrl());
                    msgType = StringValues.MSG_TYPE_VOICE;
                } else if (emMessageList.get(i).getType() == EMMessage.Type.VIDEO) {
                    msgType = StringValues.MSG_TYPE_VIDEO;
                }
                chattingBean.setType(MSG_TYPE_SEND);
            }
            chattingBean.setMsg_type(msgType);
            chattingBean.setTime(String.valueOf(emMessageList.get(i).getMsgTime()));
            chattingBean.setUsername(emMessageList.get(i).getUserName());
            chattingBean.setMUsername(mUsernmae);
            if (emMessageList.get(i).status.equals("SUCCESS")) {
                chattingBean.setStatus(0);
            } else {
                chattingBean.setStatus(1);
            }
            data.add(chattingBean);
        }

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == MSG_TYPE_RECEIVE_TXT) {//接收文本布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_receive_txt, parent, false);
            ChattingReceiveViewHolder chattingReceiveViewHolder = new ChattingReceiveViewHolder(view);
            return chattingReceiveViewHolder;
        }

        if (viewType == MSG_TYPE_RECEIVE_VOICE) {//接收语音布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_receive_voice, parent, false);
            ChattingReceiveVoiceViewHolder holder = new ChattingReceiveVoiceViewHolder(view);
            return holder;
        }

        if (viewType == MSG_TYPE_SEND_VOICE) {//发送语音布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_send_vocie, parent, false);
            ChattingSendVoiceViewHolder holder = new ChattingSendVoiceViewHolder(view);
            return holder;
        }

        if (viewType == MSG_TYPE_SEND_IMAGE) {//发送图片消息布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_send_image, parent, false);
            ChattingSendImageViewHolder chattingSendImageViewHolder =
                    new ChattingSendImageViewHolder(view);
            return chattingSendImageViewHolder;
        }

        if (viewType == MSG_TYPE_RECEIVE_IMAGE) {//接收图片消息布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_receive_image, parent, false);
            ChattingReceiveImageViewHolder chattingReceiveImageViewHolder =
                    new ChattingReceiveImageViewHolder(view);
            return chattingReceiveImageViewHolder;
        } else {//发送文本布局
            View view = LayoutInflater.from(context).inflate(
                    R.layout.item_recycle_chatting_send_txt, parent, false);
            ChattingSendViewHolder chattingSendViewHolder = new ChattingSendViewHolder(view);
            return chattingSendViewHolder;
        }

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (getItemViewType(position) == MSG_TYPE_SEND_TXT) {//发送文本消息
            ChattingSendViewHolder chattingSendViewHolder = (ChattingSendViewHolder) holder;
            chattingSendViewHolder.body.setText(data.get(position).getBody());
            chattingSendViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onChattingItemClickListener.onChattingItemLongClick(mUsernmae);
                    return false;
                }
            });
            chattingSendViewHolder.headImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onChattingItemClickListener.onHeadImgClick(mUsernmae);
                }
            });
            setSendViewCount(chattingSendViewHolder.count++);
        } else if (getItemViewType(position) == MSG_TYPE_RECEIVE_TXT) {//接收文本消息
            ChattingReceiveViewHolder chattingReceiveViewHolder = (ChattingReceiveViewHolder) holder;
            chattingReceiveViewHolder.body.setText(data.get(position).getBody());
            chattingReceiveViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onChattingItemClickListener.onChattingItemLongClick(toUserName);
                    return false;
                }
            });
            chattingReceiveViewHolder.headImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onChattingItemClickListener.onHeadImgClick(toUserName);
                }
            });
        } else if (getItemViewType(position) == MSG_TYPE_SEND_VOICE) {//发送语音消息
            final ChattingSendVoiceViewHolder sendVoiceViewHolder = (ChattingSendVoiceViewHolder) holder;
            String len = "";
            for (int i = 0; i < data.get(position).getVoiceLen(); i++) {
                if (i < 15) {
                    len += "  ";
                }
            }
            sendVoiceViewHolder.textView.setText(data.get(position).getVoiceLen() + "''" + len);
            sendVoiceViewHolder.pos = position;
            sendVoiceViewHolder.voiceBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onChattingItemClickListener.playVoice(data.get(sendVoiceViewHolder.pos).getBody());
                }
            });
        } else if (getItemViewType(position) == MSG_TYPE_RECEIVE_VOICE) {//接收语音消息
            final ChattingReceiveVoiceViewHolder receiveVoiceViewHolder = (ChattingReceiveVoiceViewHolder) holder;
            receiveVoiceViewHolder.pos = position;
            String len = "";
            for (int i = 0; i < data.get(position).getVoiceLen(); i++) {
                if (i < 15) {
                    len += "  ";
                }
            }
            receiveVoiceViewHolder.textView.setText(len + data.get(position).getVoiceLen() + "''");
            receiveVoiceViewHolder.voiceBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onChattingItemClickListener.playVoice(data.get(receiveVoiceViewHolder.pos).getBody());
                }
            });
        } else if (getItemViewType(position) == MSG_TYPE_SEND_IMAGE) {//发送图片消息
            ChattingSendImageViewHolder viewHolder = (ChattingSendImageViewHolder) holder;
            Bitmap bitmap = getLoacalBitmap(data.get(position).getBody());
            viewHolder.imageView.setImageBitmap(bitmap);
            viewHolder.imageView.setProgress(102);
            viewHolder.imageViewSuccess.setImageBitmap(bitmap);
        } else if (getItemViewType(position) == MSG_TYPE_RECEIVE_IMAGE) {//接收图片消息
            ChattingReceiveImageViewHolder viewHolder = (ChattingReceiveImageViewHolder) holder;
            RenrenxinSingleton.getInstence().loadNetWorkImage(viewHolder.imageView, data.get(position).getBody());
        }

        holder.itemView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                onChattingItemClickListener.ItemClick();
                return false;
            }
        });
    }

    @Override
    public int getItemCount() {
        return null == data ? 0 : data.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (data.get(position).getType() == MSG_TYPE_RECEIVE) {//接收
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_TXT))//文本
                return MSG_TYPE_RECEIVE_TXT;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_FILE))//文件
                return MSG_TYPE_RECEIVE_FILE;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_IMAGE))//图片
                return MSG_TYPE_RECEIVE_IMAGE;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_LOCATION))//定位
                return MSG_TYPE_RECEIVE_LOCATION;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_VIDEO))//视频
                return MSG_TYPE_RECEIVE_VIDEO;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_VOICE))//语音
                return MSG_TYPE_RECEIVE_VOICE;
        } else {//发送
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_TXT))//文本
                return MSG_TYPE_SEND_TXT;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_FILE))//文件
                return MSG_TYPE_SEND_FILE;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_IMAGE))//图片
                return MSG_TYPE_SEND_IMAGE;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_LOCATION))//定位
                return MSG_TYPE_SEND_LOCATION;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_VIDEO))//视频
                return MSG_TYPE_SEND_VIDEO;
            if (data.get(position).getMsg_type().equals(StringValues.MSG_TYPE_VOICE))//语音
                return MSG_TYPE_SEND_VOICE;
        }
        return MSG_TYPE_SEND;
    }


    private Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }


    public void notifyReceiveMsg(ChatList chat) {
        ChatList chattingBean = new ChatList();
        chattingBean.setType(MSG_TYPE_RECEIVE);
        chattingBean.setBody(chat.getBody());
        chattingBean.setMsg_type(chat.getMsg_type());
        chattingBean.setUsername(toUserName);
        data.add(chattingBean);
        notifyDataSetChanged();
    }

    public void send(ChatList chat) {
        data.add(chat);
        notifyDataSetChanged();
    }


    public int indexOfList(ChatList chat) {
        return data.indexOf(chat);
    }

    /***************************
     * 接收信息缓存类
     *******************************/
    /**
     * 接收文本
     */
    class ChattingReceiveViewHolder extends RecyclerView.ViewHolder {
        private TextView body;
        private ImageButton headImg;

        public ChattingReceiveViewHolder(View itemView) {
            super(itemView);
            body = (TextView) itemView.findViewById(R.id.tv_item_recycle_chatting_receive_txt);
            headImg = (ImageButton) itemView.findViewById(R.id.imgBtn_item_recycle_chatting_receive_txt_headimg);
        }
    }

    /**
     * 接收语音
     */
    public class ChattingReceiveVoiceViewHolder extends RecyclerView.ViewHolder {
        public ImageButton voiceBtn, headImg;
        private TextView textView;
        private int pos;

        public ChattingReceiveVoiceViewHolder(View itemView) {
            super(itemView);
            voiceBtn = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_receive_voice_content);
            headImg = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_receive_voice_headimg);
            textView = (TextView) itemView.findViewById(
                    R.id.tv_item_recycle_chatting_receive_voice_kong);
            pos = 0;
        }
    }

    /**
     * 接收图片
     */
    class ChattingReceiveImageViewHolder extends RecyclerView.ViewHolder {
        private NetworkImageView imageView;
        private ImageButton headImagBtn;
        int pos = 0;

        public ChattingReceiveImageViewHolder(View itemView) {
            super(itemView);
            imageView = (NetworkImageView) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_receive_image_content);
            headImagBtn = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_receive_image_headimg);
            pos = 0;
        }
    }

    /***************************
     * 发送信息缓存类
     *******************************/
    public class ChattingSendViewHolder extends RecyclerView.ViewHolder {
        public TextView body;
        private ImageButton headImg;
        public ProgressBar progressBar;
        private int count = 0;

        public ChattingSendViewHolder(View itemView) {
            super(itemView);
            body = (TextView) itemView.findViewById(R.id.tv_item_recycle_chatting_send);
            headImg = (ImageButton) itemView.findViewById(R.id.imgBtn_recycle_chatting_send);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progressbar_sendmsg);
            count = 0;
        }
    }

    /**
     * 接收语音缓存类
     */
    public class ChattingSendVoiceViewHolder extends RecyclerView.ViewHolder {
        public ImageButton voiceBtn, headImg;
        private TextView textView;
        private int pos;

        public ChattingSendVoiceViewHolder(View itemView) {
            super(itemView);
            voiceBtn = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_send_voice_content);
            headImg = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_send_voice_headimg);
            textView = (TextView) itemView.findViewById(
                    R.id.tv_item_recycle_chatting_send_voice_kong);
            pos = 0;
        }
    }

    /**
     * 发送图片
     */
    public class ChattingSendImageViewHolder extends RecyclerView.ViewHolder {
        private ImageButton headImgBtn;
        public ProcessImageView imageView;
        public ImageView imageViewSuccess;
        private int pos = 0;

        public ChattingSendImageViewHolder(View itemView) {
            super(itemView);
            headImgBtn = (ImageButton) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_send_image_headimg);
            imageView = (ProcessImageView) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_send_image_content_process);
            imageViewSuccess = (ImageView) itemView.findViewById(
                    R.id.imgBtn_item_recycle_chatting_send_image_content);
            pos = 0;
        }
    }
}
